package com.neusoft.liduan.d0922;

public class Demo6 {
	/*
	 * 6.生产者与消费者问题，附加题，经典面试题 生产者专门生产产品，当产品数达到20时候，则停止生产
	 * 	消费者专门消费产品，当产品少于5的时候需要告诉生产者可以生产了。
	 * 
	 */
	public static void main(String[] args) {
		Product p = new Product();
		Cust c = new Cust(p);
		c.setName("消费者");
		c.start();
		Prod pr = new Prod(p);
		pr.setName("生产者");
		pr.start();
	}
	
	private static class Product {
		private int count;//商品总数
		
		public void setCount(int count) {
			this.count = count;
		}
		
		public int getCount() {
			return count;
		}
	}
	
	private static class Cust extends Thread {
		private Product product;

		public Cust(Product product) {
			this.product = product;
		}

		@Override
		public void run() {
			while(true) {
				synchronized (product) {
					if(product.getCount() <= 5) {
						product.notify();
						try {
							product.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					product.setCount(product.getCount() - 1);
					System.out.println(currentThread().getName() + "消费了1个，剩余" + product.getCount());
					try {
						sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private static class Prod extends Thread {
		private Product product;

		public Prod(Product product) {
			this.product = product;
		}

		@Override
		public void run() {
			while(true) {
				synchronized (product) {
					if(product.getCount() >= 20) {
						product.notify();
						try {
							product.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					product.setCount(product.getCount() + 1);
					System.out.println(currentThread().getName() + "生产了1个，剩余" + product.getCount());
					try {
						sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
}
